<?php
/**
 * Created by IntelliJ IDEA.
 * User: wanglu
 * Date: 17/4/12
 * Time: 17:43
 */
class MY_Model extends CI_Model {

	
	function __construct() {
		parent::__construct();
	}

	public function getTable($tableName) {
		return$this->db-> dbprefix .$tableName;
	}
}

class BaseModel extends MY_Model {

	public $recordTable;

	function __construct($rt = NULL)
	{
		parent::__construct();
		$this->recordTable = $rt;
	}

	public function createRecord($record) {
		$this->db->insert($this->recordTable, $record);
		return $this->db->affected_rows() > 0;
	}

	public function createRecordReturnId($record) {
		$this->db->insert($this->recordTable, $record);
		return $this->db->insert_id();
	}

	public function updateRecord($record, $where = array()) {
		foreach ($record as $filed=> $value) {
			$this->db->set($filed, $value);
		}

		foreach ($where as $filed => $value) {
			$this->db->where($filed, $value);
		}

		$this->db->update($this->recordTable); // give
		return $this->db->affected_rows() > 0;
	}

	public function deleteRecord($where = array()) {
		foreach ($where as $filed => $value) {
			$this->db->where($filed, $value);
		}

		$this->db->delete($this->recordTable);
		return $this->db->affected_rows() > 0;
	}

	public function getRecord($where = array()) {
		foreach ($where as $filed => $value) {
			$this->db->where($filed, $value);
		}
		$query = $this->db->get($this->recordTable);

		return $query->row_array();
	}

	public function getRecords($where = array(), $orderby = array()) {
		foreach ($where as $filed => $value) {
			$this->db->where($filed, $value);
		}

		foreach ($orderby as $filed => $value) {
			$this->db->order_by($filed, $value);
		}

		$query = $this->db->get($this->recordTable);

	

		return $query->result_array();
	}

	protected function getOffset($page) {
		$offset = (($page >0 ? $page : 1) - 1) * $this->pageSize;
		return $offset;
	}


	public function getPageData($start, $lenght, $orderby = array()) {
		$qcount = $this->db->from($this->recordTable);
		$db = clone($this->db);
		$count = $qcount ->count_all_results();
		//echo $count;
		$this->db = $db;
		// $sql = $this->db ->limit($lenght, $start) -> get_compiled_select();
		//	echo $sql;
		//	exit;

		foreach ($orderby as $okey => $ovalue) {
			$this->db->order_by($okey, $ovalue);
		}

		$data = $this->db->limit($lenght, $start) -> get()-> result_array();

		return array("data"=> $data, "recordsTotal" => $count, "recordsFiltered" => $count);
	}




}


